package initialition

import (
	"course/global"
	"course/internal/model/dao"
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

func init() {
	InitZap()
	InitConfig()
	InitDB()
}
func InitZap() {
	os.MkdirAll("./log", 0777)
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"./log/dev.log",
	}
	build, err := config.Build()
	if err != nil {
		panic(err)
	}
	zap.ReplaceGlobals(build)
}
func InitConfig() {
	viper.SetConfigFile("./config/config.dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.Config)
	fmt.Println("配置解析参数", global.Config)
}
func InitDB() {
	var err error
	config := global.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.Username, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql连接成功")
	global.DB.AutoMigrate(&dao.Course{}, &dao.Reservation{})
}
